import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import java.util.EventListener;


@SuppressWarnings("serial")
public class DrawingCanvas extends JComponent {

  protected Image imageBuffer;
  protected Graphics imageBufferGraphics;
  public IDrawingObjectLink firstObject;
  protected int canvasWidth;
  protected int canvasHeight;
  protected Color penColor = Color.black;
  protected Tool currentTool;
  IDrawingObject magicBox;
  
  /* constructor */
  public DrawingCanvas() {
	setCurrentTool(new FreehandTool(this));
    setBackground(Color.white);
    firstObject=new IDrawingObjectLink(new SelectionBox(this));
    magicBox=firstObject.o;
  }

  protected void addDrawingCanvasListener(EventListener listener) {
    addMouseListener((MouseListener) listener);
    addMouseMotionListener((MouseMotionListener) listener);
  }
  
  public void addKeyboardListener(EventListener listener) {
	    addKeyListener( (KeyListener)listener);
  }

  public void update(Graphics g){
     paint(g);
  }
  public void paint(Graphics g) {
	  imageBuffer = createImage(canvasWidth, canvasHeight);
	  imageBufferGraphics = imageBuffer.getGraphics();
	  IDrawingObjectLink current=firstObject;
	 while(current!=null){
    	 current.o.drawMe(imageBufferGraphics);
    	 current=current.next;
     }
	  
	 g.drawImage(imageBuffer,0, 0, this);
  }
  
  public void drawLineSegment(Point p1, Point p2) {
   imageBufferGraphics.drawLine(p1.x,p1.y,p2.x, p2.y);
   repaint();
  }

  public void setBounds(int x, int y, int width, int height) {
    if(width<=0)width=1;
    if(height<=0)height=1;
    imageBuffer = createImage(width, height);
    imageBufferGraphics = imageBuffer.getGraphics();
    
    super.setBounds(x, y, width, height);
    repaint();
    canvasWidth = width;
    canvasHeight = height;
  }
  public void setPenColor(Color c) {
	    penColor = c;
	    imageBufferGraphics.setColor(penColor);
  }
  
  public void clearCanvas() {
	   imageBuffer = createImage(canvasWidth, canvasHeight);
	   imageBufferGraphics = imageBuffer.getGraphics();
	   firstObject=new IDrawingObjectLink(new SelectionBox(this));
	   //repaint();
	  }
  
  
  
  public Graphics getImageBufferGraphics() {
	    return imageBufferGraphics; 
	  }

  public Tool getCurrentTool() {
	    return currentTool;
	  }

	  public void setCurrentTool(Tool tool) {
	    currentTool = tool;
	  }
  
}
